//
//  RHPlantTransferVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/11/7.
//

#import "RHPlantTransferVC.h"
#import "LCMD5Tool.h"
#import "CDZQRScanViewController.h"
#import "RHNavigationController.h"

@interface RHPlantTransferVC ()<UITableViewDelegate,UITableViewDataSource,QMUITextFieldDelegate>
@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic, strong) NSArray *dataArr;

@property (nonatomic, strong) NSArray *keyArr;

@property (nonatomic, strong) NSDictionary *dic;

@property (nonatomic, strong) QMUITextField *emailTFD;
@end

@implementation RHPlantTransferVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = @"电站转让".rh_localized;
    self.dataArr = @[@"用户名".rh_localized,@"用户昵称".rh_localized,@"上级用户".rh_localized,@"用户地址".rh_localized];
    self.keyArr = @[@"userName",@"nickName",@"superUser",@"address"];
    [self setupUI];
}


-(void)setupUI
{
    UIView *topBgView = kView;
    [self.view addSubview:topBgView];
    topBgView.backgroundColor = [UIColor whiteColor];
    topBgView.layer.cornerRadius = 8;
    topBgView.layer.masksToBounds = YES;
    
    QMUILabel *titleLab = [[QMUILabel alloc]init];
    titleLab.text = @"转让给".rh_localized;
    titleLab.font = [UIFont systemFontOfSize:15];
    titleLab.textColor = kCOLOR_HEX(@"969799");
    [topBgView addSubview:titleLab];
    
    QMUITextField *emailTFD = [[QMUITextField alloc]init];
    emailTFD.placeholder = @"请输入接收者的邮箱".rh_localized;
    emailTFD.textAlignment = NSTextAlignmentRight;
    emailTFD.font = [UIFont systemFontOfSize:15];
    emailTFD.returnKeyType = UIReturnKeyDone;
    [topBgView addSubview:emailTFD];
    self.emailTFD = emailTFD;
    emailTFD.delegate = self;
    
    UIView *btnView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnView addSubview:btn];
    [btn setFrame:CGRectMake(10, 10, 20, 20)];
    [btn setImage:[UIImage imageNamed:@"input_scan_icon"] forState:UIControlStateNormal];
    emailTFD.rightView = btnView;
    [emailTFD setRightViewMode:UITextFieldViewModeAlways];
    [btn addTarget:self action:@selector(scanQRC) forControlEvents:UIControlEventTouchUpInside];
    
    [topBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_offset(15);
        make.right.mas_offset(-15);
    }];
    
    [titleLab sizeToFit];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(20);
        make.centerY.equalTo(emailTFD);
        make.width.offset(titleLab.width+1);
    }];
    
    [emailTFD mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLab.mas_right).offset(15);
        make.top.mas_offset(10);
        make.right.mas_offset(-10);
        make.height.offset(45);
        make.bottom.mas_offset(-10);
    }];
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 120, 120) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.layer.cornerRadius = 5;
    _tableView.layer.masksToBounds = YES;
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(topBgView.mas_bottom).offset(15);
        make.height.offset(44*self.dataArr.count);
    }];
    
    QMUIButton *sureBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [sureBtn setTitle:@"确定".rh_localized forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sureBtn setCornerRadius:8];
    [sureBtn setBackgroundColor:CMainColorGreen];
    [self.view addSubview:sureBtn];
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(20);
            make.right.mas_offset(-20);
            make.bottom.mas_offset(-kSafe_bottom-20);
            make.height.offset(kScaleW(45));
    }];
    [sureBtn addTarget:self action:@selector(clickButton) forControlEvents:UIControlEventTouchUpInside];
    
//    self.tableView.hidden = YES;
}


#pragma mark ---- 确定转让
-(void)clickButton
{
    kWeakSelf;
    QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"确定转让?".rh_localized message:@"此操作不可逆,请谨慎操作!".rh_localized preferredStyle:QMUIAlertControllerStyleAlert];
    [alertController addAction:[QMUIAlertAction actionWithTitle:@"确定".rh_localized style:QMUIAlertActionStyleDestructive handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        [QMUITips showLoadingInView:weakSelf.view];
        QMUITextField *textField = [aAlertController.textFields firstObject];
        [BaseModel startWithCompletionAPIKey:H_transferPlant argument:@{@"plantId":@(self.plantId),@"password":[LCMD5Tool md5HexDigest:[textField text]],@"userId":@([self.dic[@"userId"] integerValue])} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
            if(resultModel.code == 200){
                [QMUITips showSucceed:@"成功".rh_localized];
                [[NSNotificationCenter defaultCenter]postNotificationName:PlantListNeedUpdateNotification object:nil];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                    if (self.transferBlock) {
                        self.transferBlock();
                    }
                });
                
            }
            
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
        }];
       
    }]];
    QMUIAlertAction *action = [QMUIAlertAction actionWithTitle:@"取消".rh_localized style:QMUIAlertActionStyleCancel handler:nil];
    [alertController addAction:action];
    [alertController addTextFieldWithConfigurationHandler:^(QMUITextField * _Nonnull textField) {
        textField.placeholder = @"请输入密码".rh_localized;
    }];
    [alertController showWithAnimated:YES];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    id value =  self.dic[self.keyArr[indexPath.row]];
    cell.detailTextLabel.text = ValidNullDataToString(value, @"--");
    cell.textLabel.text = self.dataArr[indexPath.row];
    cell.textLabel.textColor = kCOLOR_HEX(@"969799");
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    
    cell.detailTextLabel.font = [UIFont systemFontOfSize:14];
    cell.detailTextLabel.textColor = kCOLOR_HEX(@"969799");
    
    UIView *line = kView;
    line.backgroundColor = [UIColor colorWithHexString:@"000000" alpha:0.1];
    [cell.contentView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.bottom.mas_offset(0);
        make.height.offset(1);
    }];
    if (indexPath.row == self.dataArr.count-1) {
        UIView *line = kView;
        line.backgroundColor = UIColor.whiteColor;
        [cell.contentView addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(10);
            make.right.mas_offset(-10);
            make.height.offset(1);
            make.bottom.mas_offset(0);
        }];
    }
    return cell;
}


#pragma mark ------- 转让电站 -------
-(void)transferPlant
{
    kWeakSelf;
    QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"电站转让".rh_localized message:@"" preferredStyle:QMUIAlertControllerStyleAlert];
    [alertController addAction:[QMUIAlertAction actionWithTitle:@"确定".rh_localized style:QMUIAlertActionStyleDestructive handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        QMUITextField *textField = [aAlertController.textFields firstObject];
       
        [weakSelf getUserInfoWithEmail:textField.text];
       
    }]];
    QMUIAlertAction *action = [QMUIAlertAction actionWithTitle:@"取消".rh_localized style:QMUIAlertActionStyleCancel handler:nil];
    [alertController addAction:action];
    [alertController addTextFieldWithConfigurationHandler:^(QMUITextField * _Nonnull textField) {
        textField.placeholder = @"请输入用户邮箱".rh_localized;
    }];

    [alertController showWithAnimated:YES];
    

}

-(void)getUserInfoWithEmail:(NSString *)email
{
    [QMUITips showLoadingInView:self.view];
    [BaseModel startGetWithCompletionAPIKey:H_transferPlantUser argument:@{@"account":email} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
    
            self.dic = request.responseJSONObject[@"data"];
            [self.tableView reloadData];
//            self.tableView.hidden = self.dic.allKeys.count == 0;
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

#pragma mark ----- 检查二维码信息 ----------
-(void)checkContent:(NSString *)content
{
    NSLog(@"---->扫描到的信息:%@",content);
    NSData *jsonData = [content dataUsingEncoding:NSUTF8StringEncoding];
    
    if(jsonData == nil){
        [QMUITips showError:@"数据错误".rh_localized];
        return;
    }
    
    NSError *error= nil;
    NSDictionary *dicInfo = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    if (![dicInfo isKindOfClass:[NSDictionary class]]){
        [QMUITips showError:@"数据格式错误".rh_localized];
        return;
    }
    if(dicInfo[@"QRCode"] && [dicInfo[@"userType"] integerValue] == (NSInteger)UserRoleTypeTerminalUser){
        // && [dicInfo[@"userType"] integerValue] == (NSInteger)UserRoleTypeTerminalUser
        NSString *qrCode_content = dicInfo[@"QRCode"];
        //base64 解码
        NSData* qrCode_Data = [[NSData alloc] initWithBase64EncodedString:qrCode_content options:0];
        
        NSDictionary *qrCode_Dic = [NSJSONSerialization JSONObjectWithData:qrCode_Data options:NSJSONReadingMutableContainers error:&error];
        
        if(qrCode_Dic[@"email"]){
            self.emailTFD.text = qrCode_Dic[@"email"];
            
            [self getUserInfoWithEmail:ValidNullData(qrCode_Dic[@"email"])];
        }else{
            [QMUITips showError:@"没有相关信息".rh_localized];
        }
        
        
    }else{
        [QMUITips showError:@"数据错误".rh_localized];
    }
    
    
    
}
#pragma mark ------ 扫描二维码

- (void)scanQRC{
    if ([self isCameraAvailable]) {
        [self isCanVisitPhotoAndCameraAuthorization:^(BOOL isOK,NSString *alerStr) {
            if (isOK) {
                NSLog(@"权限OK");
                kWeakSelf;
                CDZQRScanViewController *controller = [[CDZQRScanViewController alloc] init];
                controller.resultCallBack = ^(NSString *content) {
                    [weakSelf checkContent:content];
                };
                 RHNavigationController *nav = [[RHNavigationController alloc] initWithRootViewController:controller];
                [nav setModalPresentationStyle:UIModalPresentationOverFullScreen];
                [self presentViewController:nav animated:YES completion:^{
                    
                }];
            }else{
                if (alerStr) {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:alerStr preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *conform = [UIAlertAction actionWithTitle:@"去设置".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                         if (@available(iOS 10.0, *)) {
                             [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
                             } else {
                             NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                             if ([[UIApplication sharedApplication] canOpenURL:url]) {
                                 [[UIApplication sharedApplication] openURL:url];
                             }
                         }
                    }];
                    
                    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        NSLog(@"点击了取消按钮");
                    }];
                    [alert addAction:cancel];
                    [alert addAction:conform];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }
        }];
    }else{
        NSLog(@"摄像头不可用");
    }

}

// 判断设备是否有摄像头
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}
- (void)isCanVisitPhotoAndCameraAuthorization:(void(^)(BOOL isOK,NSString *alerStr))result {
    PHAuthorizationStatus photo_status = [PHPhotoLibrary authorizationStatus];
    AVAuthorizationStatus camera_status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (photo_status == PHAuthorizationStatusAuthorized&&camera_status ==AVAuthorizationStatusAuthorized) {
        result(YES,nil);
        return;
    }
    
    if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied||
        camera_status ==AVAuthorizationStatusDenied || camera_status ==AVAuthorizationStatusRestricted) {
        if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied) {
            result(NO,@"Please allow access photos in iPhone's Settings");
        }else{
            result(NO,@"Please allow access camera in iPhone's Settings");
        }
        return ;
    }
    
    if (camera_status == AVAuthorizationStatusNotDetermined) {
        //点击弹框授权
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(!granted){//不允许
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"未开启相机权限,请到设置中开启");
                    result(NO,nil);
                });
            }else{
                if (photo_status == PHAuthorizationStatusNotDetermined) {
                    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                               // 回调是在子线程的
                               NSLog(@"%@",[NSThread currentThread]);
                               dispatch_async(dispatch_get_main_queue(), ^{
                                   if (status != PHAuthorizationStatusAuthorized) {
                                         NSLog(@"未开启相册权限,请到设置中开启");
                                         result(NO,nil);
                                   }else{
                                         result(YES,nil);
                                   }
                               });
                     
                           }];
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        result(YES,nil);
                    });
                }

            }
        }];
        return;
    }
    
    if (photo_status == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                   // 回调是在子线程的
                   NSLog(@"%@",[NSThread currentThread]);
                   dispatch_async(dispatch_get_main_queue(), ^{
                       if (status != PHAuthorizationStatusAuthorized) {
                             NSLog(@"未开启相册权限,请到设置中开启");
                             result(NO,nil);
                       }else{
                             result(YES,nil);
                       }
                   });
               }];
    }
}


#pragma mark ---------- textField delegate -----
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if(textField.text.length>0){
        [self getUserInfoWithEmail:textField.text];
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if(textField.text.length>0){
        [self getUserInfoWithEmail:textField.text];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [textField resignFirstResponder];
    });
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
//    self.tableView.hidden = YES;
    self.dic = @{};
    [self.tableView reloadData];
    return YES;
}
@end
